﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace WXY.Course.Common.MVCExtension
{
    internal abstract class Pager
    {
        protected StringBuilder htmlAppender = new StringBuilder();
        protected string pageField = "page";
        protected string actionName;
        protected string controllerName;
        protected PagerConfig config;
        protected int[] pageNumbers;
        protected UrlHelper urlHelper;
        
        protected Pager(HtmlHelper htmlHelper, PagerConfig pageConfig)
        {
            this.config = pageConfig;
            this.pageNumbers = ComputePageNumbers(config.CurrentPage, config.LastPage, config.PageBarLength);
            this.urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        }

        //创建分页页码序列
        private int[] ComputePageNumbers(int curPage, int maxPage, int pageBarLength)
        {
            //创建以当前页为中心，以分页条一半长度为半径的有序对称列表。
            var list = CreateSymmetricOrderedList(curPage, pageBarLength / 2);

            for (var i = 0; i < pageBarLength; i++)
            {
                //每出现一个非正数，就在表尾追加【最大值+1】的数。
                if (list[i] < 1) list.Add(list.Last() + 1);

                //每出现一个大于最大页码的数，就在表头插入【最小值-1】的数
                else if (list[i] > maxPage) list.Insert(0, list.First() - 1);
            }
            return list.Where(p => p > 0 && p <= maxPage).ToArray();
        }
        private List<int> CreateSymmetricOrderedList(int center, int radius)
        {
            var list = new List<int>();
            for (var i = center - radius; i < center + radius; i++) list.Add(i);
            return list;
        }

        public abstract string Render();
    }
}
